package me.phelps.webrtctest;

import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaRecorder;
import android.media.audiofx.AutomaticGainControl;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 * Created by User on 2016/11/3.
 */

public class AudioHelper implements AudioConstants{



    public static ExecutorService executor = Executors.newCachedThreadPool();

    public static int getRecordMinBufferSize(){
        return AudioRecord.getMinBufferSize(
                SAMPLE_RATE,
                AudioFormat.CHANNEL_IN_MONO,
                AudioFormat.ENCODING_PCM_16BIT);
    }

    public static AudioRecord createAudioRecord(int minBufferSize){
        return new AudioRecord(
                MediaRecorder.AudioSource.MIC,
                SAMPLE_RATE,
                AudioFormat.CHANNEL_IN_MONO,
                AudioFormat.ENCODING_PCM_16BIT,
                minBufferSize*2
        );
    }

    public static void enableAgc(int sessionId,boolean enable){
        if(AutomaticGainControl.isAvailable()){
            AutomaticGainControl agc = AutomaticGainControl.create(sessionId);
            agc.setEnabled(enable);
        }
    }

    public static void stopRecord(AudioRecord audioRecord){
        if(audioRecord!=null){
            audioRecord.stop();
            audioRecord.release();
            audioRecord = null;
        }
    }

    public static int getTrackMinBufferSize(){
        return AudioTrack.getMinBufferSize(
                SAMPLE_RATE,
                AudioFormat.CHANNEL_OUT_MONO,
                AudioFormat.ENCODING_PCM_16BIT);
    }

    public static AudioTrack createAudioTrack(int minBufferSize){
        return new AudioTrack(
                AudioManager.STREAM_MUSIC,
                SAMPLE_RATE,
                AudioFormat.CHANNEL_OUT_MONO,
                AudioFormat.ENCODING_PCM_16BIT,
                minBufferSize,
                AudioTrack.MODE_STREAM
        );
    }

    public static void stopTrack(AudioTrack audioTrack){
        if(audioTrack!=null){
            audioTrack.stop();
            audioTrack.release();
            audioTrack = null;
        }
    }

}
